import React, { useEffect, useState } from 'react'
import { Header, TabBar } from 'src/components'
import { useParams, Link } from 'react-router-dom'
import { searchRestaurant } from 'src/api/getData'
import { imgBaseUrl } from '../../config/env'
import { getStore, setStore } from '../../config/mUtils'

import './index.scss'
import { useSelector } from 'react-redux'

const Search = () => {
    const { geohash } = useSelector(state => state)
    const [searchValue, setSearchValue] = useState('') // 搜索内容
    const [restaurantList, setRestaurantList] = useState([])// 搜索返回的结果
    const [searchHistory, setSearchHistory] = useState([])// 搜索历史记录
    const [showHistory, setShowHistory] = useState(true) // 是否显示历史记录，只有在返回搜索结果后隐藏
    const [emptyResult, setEmptyResult] = useState(false)// 搜索结果为空时显示

    useEffect(() => {
        //获取搜索历史记录
        if (getStore('searchHistory')) {
            setSearchHistory(JSON.parse(getStore('searchHistory')));
        }
    }, [])

    //点击提交按钮，搜索结果并显示，同时将搜索内容存入历史记录
    const searchTarget = async (historyValue) => {
        if (historyValue) {
            setSearchValue(historyValue)
        } else if (!searchValue) {
            return
        }
        //隐藏历史记录
        setShowHistory(false)
        //获取搜索结果
        let res = await searchRestaurant(geohash, searchValue)
        setRestaurantList(res.data)
        setEmptyResult(!res.data.length)
        /**
         * 点击搜索结果进入下一页面时进行判断是否已经有一样的历史记录
         * 如果没有则新增，如果有则不做重复储存，判断完成后进入下一页
         */
        let history = getStore('searchHistory');
        if (history) {
            let checkrepeat = false;
            let historyNew = JSON.parse(history)
            historyNew.forEach(item => {
                if (item === searchValue) {
                    checkrepeat = true;
                }
            })
            if (!checkrepeat) {
                historyNew.push(searchValue)
            }
            setSearchHistory(historyNew)
            setStore('searchHistory', historyNew)
        } else {
            setSearchHistory([...searchHistory, searchValue])
            setStore('searchHistory', [...searchHistory, searchValue])
        }

    }
    //搜索结束后，删除搜索内容直到为空时清空搜索结果，并显示历史记录
    const checkInput = (value) => {
        if (value === '') {
            setShowHistory(true) //显示历史记录
            setRestaurantList([]) //清空搜索结果
            setEmptyResult(false)//隐藏搜索为空提示
        }
    }
    //点击删除按钮，删除当前历史记录
    const deleteHistory = (index) => {
        let searchHistoryNew = searchHistory.splice(index, 1);
        setSearchHistory(searchHistoryNew)
        setStore('searchHistory', searchHistoryNew);
    }
    //清除所有历史记录
    const clearAllHistory = () => {
        setSearchHistory([])
        setStore('searchHistory', []);
    }

    return <div className="paddingTop page_search">
        <Header title="搜索" goBack />
        <form className="search_form">
            <input type="search" name="search" placeholder="请输入商家或美食名称" className="search_input" value={searchValue}
                onInput={(e) => {
                    setSearchValue(e.target.value)
                    checkInput(e.target.value)
                }}
            />
            <input type="submit" name="submit" className="search_submit" onClick={(e) => {
                e.preventDefault();
                searchTarget('')
            }} />
        </form>
        {
            restaurantList.length > 0 && <section>
                <h4 className="title_restaurant">商家</h4>
                <ul className="list_container">
                    {
                        restaurantList.map(item => {
                            return <li
                                key={item.id}
                                className="list_li">
                                <Link to={`/shop?id=${item.id}`} >
                                    <section className="item_left">
                                        <img src={`${imgBaseUrl}${item.image_path}`} className="restaurant_img" alt="" />
                                    </section>
                                    <section className="item_right">
                                        <div className="item_right_text">
                                            <p>
                                                <span>{item.name}</span>
                                                <svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="24" height="14" className="pay_icon">
                                                    <polygon points="0,14 4,0 24,0 20,14"
                                                        style={{
                                                            fill: 'none',
                                                            stroke: '#FF6000',
                                                            strokeWidth: 1
                                                        }}
                                                    />
                                                    <line x1="1.5" y1="12" x2="20" y2="12" style={
                                                        {
                                                            stroke: '#FF6000',
                                                            strokeWidth: 1.5
                                                        }
                                                    } />
                                                    <text x="3.5" y="9" style={{
                                                        fill: '#FF6000',
                                                        fontSize: 9,
                                                        fontWeight: 'bold'
                                                    }}>支付</text>
                                                </svg>
                                            </p>
                                            <p>月售 {item.month_sales || item.recent_order_num} 单</p>
                                            <p>{item.delivery_fee || item.float_minimum_order_amount} 元起送 / 距离{item.distance}</p>
                                        </div>
                                        <ul className="item_right_detail">
                                            {
                                                item.restaurant_activity && item.restaurant_activity.map((activities) => {
                                                    return <li key={activities.id}>
                                                        <span style={
                                                            {
                                                                backgroundColor: '#' + activities.icon_color
                                                            }} className="activities_icon">{activities.icon_name}</span>
                                                        <span>{activities.name}</span>
                                                        <span className="only_phone">(手机客户端专享)</span>
                                                    </li>
                                                })
                                            }

                                        </ul>
                                    </section>
                                </Link>
                            </li>
                        })
                    }
                </ul>
            </section>
        }
        {
            searchHistory.length > 0 && showHistory && <section className="search_history">
                <h4 className="title_restaurant">搜索历史</h4>
                <ul>
                    {
                        searchHistory.map((item, index) => {
                            return <li key={index} className="history_list">
                                <span className="history_text ellipsis" onClick={() => { searchTarget(item) }}>{item}</span>
                                <svg xmlns="http://www.w3.org/2000/svg" version="1.1" className="delete_icon" onClick={() => deleteHistory(index)}>
                                    <line x1="8" y1="8" x2="18" y2="18"
                                        style={{
                                            stroke: '#999',
                                            strokeWidth: 3
                                        }}
                                    />
                                    <line x1="18" y1="8" x2="8" y2="18" style={{
                                        stroke: '#999',
                                        strokeWidth: 3
                                    }} />
                                </svg>
                            </li>
                        })
                    }

                </ul>
                <footer className="clear_history" onClick={clearAllHistory}>清空搜索历史</footer>
            </section>
        }
        {
            emptyResult && <div className="search_none" >很抱歉！无搜索结果</div>
        }
        <TabBar />
    </div>
}

export default Search